package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: PingPongLockCondition
 * Version: 1.0.0
 * Date: 2025/5/14
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PingPongLockCondition {

    private final Lock lock = new ReentrantLock();
    private final Condition pingCond = lock.newCondition();
    private final Condition pongCound = lock.newCondition();
    private boolean pingTurn = true;

    public void ping() throws InterruptedException{
        lock.lock();
        try{
            while(!pingTurn){
                pingCond.await();
            }
            System.out.println("ping");
            pingTurn = false;
            pongCound.signal();
        }finally {
            lock.unlock();
        }
    }

    public void pong() throws InterruptedException{
        lock.lock();
        try{
            while(pingTurn){
                pongCound.await();
            }
            System.out.println("pong");
            pingTurn = true;
            pingCond.signal();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PingPongLockCondition pp = new PingPongLockCondition();
        Thread t1 = new Thread(() -> {
            try{
                for(int i = 0; i < 10; i++){
                    pp.ping();
                }
            }catch(InterruptedException e){
                Thread.currentThread().interrupt();
            }
        });

        Thread t2 = new Thread(() ->{
           try{
               for(int i = 0; i < 10; i++){
                   pp.pong();
               }
           } catch (InterruptedException e) {
               Thread.currentThread().interrupt();
           }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}
